﻿using MakeItWeb.Framework;
using System;
using System.Linq;
using System.Web;
using Telerik.Web.UI;
using System.Web.UI.WebControls;

namespace AllNations.UI
{
    public partial class PhotoAlbum : MakeItWebPage, IDynamicPage
    {
        Photoalbum _SelectedPhotoAlbum;
        Photo _SelectedPhoto;
        int _ListIndex = 0;
        int _ListIndex2 = 0;

        public PhotoAlbum()
        {
            UseQueryString = false;
        }

        public override bool IsPageAdministrator()
        {
            return IsInRole("Administrator") || IsInRole("PhotoAdmin");
        }

        public override string SelectedSection
        {
            get
            {
                return "Fellowship";
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack && !string.IsNullOrEmpty(Request.QueryString["PhotoalbumId"]))
            {
                Server.Transfer(CurrentHtmlPage.PageUrl, true);
            }
            else if (!IsPostBack && Request.Url.AbsoluteUri.Contains("&PhotoalbumId="))
            {
                string query = "&PhotoalbumId=";
                int iIndex = Request.Url.AbsoluteUri.IndexOf(query);
                SelectedPhotoAlbum = Photoalbum.GetPhotoalbum(new Guid(Request.Url.AbsoluteUri.Substring(iIndex + query.Length)));
            }
            SelectCurrentView();
        }

        private void SelectCurrentView()
        {
            GalleryViews.SelectedIndex = SelectedPhotoAlbum == null ? AlbumListView.Index :
                SelectedPhoto == null ? AlbumView.Index : PhotoView.Index;
        }

        void lnkSelectedAlbumTitle_Click(object sender, EventArgs e)
        {
            SelectedPhoto = null;
            SelectCurrentView();
        }

        private Photoalbum SelectedPhotoAlbum
        {
            get
            {
                if (_SelectedPhotoAlbum != null)
                    return _SelectedPhotoAlbum;

                if (ViewState["CurrentPhotoalbumId"] != null)
                    _SelectedPhotoAlbum = Photoalbum.GetPhotoalbum((Guid)ViewState["CurrentPhotoalbumId"]);

                return _SelectedPhotoAlbum;
            }
            set
            {
                _SelectedPhotoAlbum = value;
                ViewState["CurrentPhotoalbumId"] = value.PhotoalbumId;
            }
        }

        public Photo SelectedPhoto 
        { 
            get
            {
                if (_SelectedPhoto != null)
                    return _SelectedPhoto;

                if (ViewState["CurrentPhotoId"] != null)
                    _SelectedPhoto = Photo.GetPhoto((Guid)ViewState["CurrentPhotoId"]);

                return _SelectedPhoto;
            }
            set
            {
                _SelectedPhoto = value;
                if (value != null)
                    ViewState["CurrentPhotoId"] = value.PhotoId;
                else
                    ViewState.Remove("CurrentPhotoId");
            }
        }

        protected void menuAdmin_ItemClick(object sender, RadMenuEventArgs e)
        {
            switch (e.Item.Value)
            {
                case "AddAlbum":
                    Response.Redirect(string.Format("/WebAppAdmin/PhotoManager.aspx?HtmlPageId={0}", CurrentHtmlPage.HtmlPageId), true);
                    break;
            }
        }

        protected void menuAlbumAdmin_ItemClick(object sender, RadMenuEventArgs e)
        {
            switch (e.Item.Value)
            {
                case "ManageAlbum":
                    Response.Redirect(string.Format("/WebAppAdmin/PhotoManager.aspx?HtmlPageId={0}&PhotoalbumId={1}", CurrentHtmlPage.HtmlPageId, SelectedPhotoAlbum.PhotoalbumId), true);
                    break;
            }
        }

        protected void lnkPhotoAlbum_Click(object sender, EventArgs e)
        {
            Guid guidPhotoalbumId = new Guid((sender as LinkButton).CommandArgument);
            SelectedPhotoAlbum = Photoalbum.GetPhotoalbum(guidPhotoalbumId);
            GalleryViews.SelectedIndex = AlbumView.Index;
        }

        protected void lnkPhotoDetail_Click(object sender, EventArgs e)
        {
            Guid guidPhotoId = new Guid((sender as LinkButton).CommandArgument);
            SelectedPhoto = Photo.GetPhoto(guidPhotoId);
            GalleryViews.SelectedIndex = PhotoView.Index;
        }

        protected void linkPhoto_OnClick(object sender, EventArgs e)
        {
            ImageButton button = sender as ImageButton;
            //PhotoId = new Guid(button.CommandArgument.ToString());
            //UpdateSelectedPhoto();
            //CurrentView = AlbumView.ItemView;
        }

        protected void lnkPreviousPhoto_Click(object sender, EventArgs e)
        {
            var q = SelectedPhotoAlbum.AlbumPhotos.Select(p => p.PhotoId == SelectedPhoto.PhotoId);
            for (int i = 0; i < q.Count(); i++)
            {
                if (q.ElementAt(i) == true)
                {
                    SelectedPhoto = SelectedPhotoAlbum.AlbumPhotos.ElementAt(i - 1);
                    break;
                }
            }
        }

        protected void lnkNextPhoto_Click(object sender, EventArgs e)
        {
            var q = SelectedPhotoAlbum.AlbumPhotos.Select(p => p.PhotoId == SelectedPhoto.PhotoId);
            for (int i = 0; i < q.Count(); i++)
            {
                if (q.ElementAt(i) == true)
                {
                    SelectedPhoto = SelectedPhotoAlbum.AlbumPhotos.ElementAt(i+1);
                    break;
                }
            }
        }

        protected void pldEndofColumn_PreRender(object sender, EventArgs e)
        {
            _ListIndex2++;
            if (_ListIndex2 % 3 == 0)
                (sender as PlaceHolder).Controls.Add(new Literal() { Text = @"<div class=""endcolumns""></div>" });
            else
                (sender as PlaceHolder).Controls.Clear();
        }

        protected string GetStyle()
        {
            _ListIndex++;
            return (_ListIndex % 3 == 0) ? "column grid_33 last" : "column grid_33";
        }

        protected override void OnPreRender(EventArgs e)
        {
            ClearAdminFunctions();

            ClientScript.RegisterStartupScript(GetType(), "CurrentHtmlPageId", string.Format(@"function GetCurrentHtmlPageId() {{ return ""{0}""; }}", CurrentHtmlPage.HtmlPageId), true);
            if (SelectedPhotoAlbum != null)
                ClientScript.RegisterStartupScript(GetType(), "CurrentPhotoalbumId", string.Format(@"function GetCurrentPhotoalbumId() {{ return ""{0}""; }}", SelectedPhotoAlbum.PhotoalbumId), true);

            if (GalleryViews.SelectedIndex == AlbumListView.Index)
            {
                dlPhotoAlbum.DataSource = Photoalbum.ListPhotoalbum(CurrentHtmlPage.HtmlPageId);
                dlPhotoAlbum.DataBind();
                RegisterAdminFunction("Add new photo album", "javascript:AddPhotoAlbum(); void(0);", "~/Images/plus-icon.png");
            }
            else if (GalleryViews.SelectedIndex == AlbumView.Index)
            {
                dlPhoto.DataSource = SelectedPhotoAlbum.AlbumPhotos;
                dlPhoto.DataBind();
                lblDescription.Text = SelectedPhotoAlbum.DescTxt;
                RegisterAdminFunction("Add photo", "javascript:AddPhotoToAlbum(); void(0);", "~/Images/plus-icon.png");
                RegisterAdminFunction("Properties", "javascript:OpenAlbumProperties(); void(0);", "~/Images/edit.gif");
            }
            else if (GalleryViews.SelectedIndex == PhotoView.Index)
            {
                imgSelectedPhoto.ImageUrl = string.Format("/PhotoHandler.ashx?Size=640&PhotoId={0}", SelectedPhoto.PhotoId);
                lblSelectedPhotoTitle.Text = SelectedPhoto.TitleTxt;
                lblSelectedPhotoDesc.Text = SelectedPhoto.DescTxt;
                lnkNextPhoto.Enabled = SelectedPhotoAlbum.AlbumPhotos.Last().PhotoId != SelectedPhoto.PhotoId;
                lnkPreviousPhoto.Enabled = SelectedPhotoAlbum.AlbumPhotos.First().PhotoId != SelectedPhoto.PhotoId;
            }
            base.OnPreRender(e);
        }

        string IDynamicPage.GetPageConfigurationControl()
        {
            return string.Empty;
        }

        string IDynamicPage.PageTypeName
        {
            get { return "Photo Album"; }
        }
    }
}